// utils.ts 
import { DiZhi, SixRentData,  SixGod, SixKeys, SixRen, WuXing, FiveStars, WxShengKe, Bagua, BaguaProperty, BaguaOrientation, yinYang, FiveStarsWuXing, SixGodWuXing, visceraKeys, Viscera, Kinsfolk, Trunk } from '../model/LSRModel';
export class LSRUtils {


  static getEnumKeyByValue(enumObj: any, value: number): string | undefined {
    return Object.keys(enumObj).find(key => enumObj[key] === value);
  }

  static getEnum(enumObj: any, value: number): any | undefined {
    return enumObj[value] as FiveStars;
  }


  //static sixKeys = ['大安', '留恋', '速喜', '赤口', '小吉', '空亡'];
  static getShichen(hour: number): number {
    // 将小时调整到23点开始的时辰计算
    let adjustedHour = (hour + 1) % 24; // 23点为子时的开始，+1调整到正确的时辰
    let currentBranchIndex = Math.floor(adjustedHour / 2);
    return currentBranchIndex;
    // let shichen = LSRUtils.earthlyBranches[currentBranchIndex] + "时"; // 获取当前时辰名称

  }

  static getShike(hour: number, minute: number): number {
    // 将小时调整到23点开始的时辰计算
    let adjustedHour1 = (hour + 1) % 24;
    let totalMinutes = (adjustedHour1 * 60 + minute) % 120; // 每个时辰内的总分钟数
    // 计算当前时辰内的时刻（每 10 分钟一个时刻）
    let moment = Math.floor(totalMinutes / 10) + 1;
    return moment;
    // let shike = LSRUtils.earthlyBranches[moment] + "刻"; // 获取当前时刻名称  
  }

  /**
   * 
   * @param num 
   * @returns 
   */
  static getSixData(num: number) {
    let i = num % 6;
    return SixKeys[i];
  }


  /**
   * 八卦对应方位属性卦爻
   * 
   * 乾天 坤地  巽风 艮山  坎水  离火 兑泽  震雷
   * 先有数为先天，先有象为后天
   * 一数坎兮二数坤，三震四巽数中分。五守中宫，六乾是，七兑八艮九离门。
   * @returns 
   */
  static getBagua(): { [key: string]: Bagua } {
    let map: { [key: string]: Bagua } = {
      qian: { 
      xtIndex:1,
      htIndex:6,
      name:'乾',
      wuxing:WuXing.JIN,
      property:BaguaProperty.tian,//八卦属性 
      orientation:BaguaOrientation.xibei,//八卦方位
      trigram:[yinYang.yang,yinYang.yang,yinYang.yang],//三爻 
      viscera:[Viscera.dachang],//内脏
      kinsfolk:Kinsfolk.fu,//对应亲属
      trunk:Trunk.tou,//对应躯干
   


    },
    dui:
    { 
      xtIndex:2,
      htIndex:7,
      name:'兑',
      wuxing:WuXing.JIN,
      property:BaguaProperty.ze,//八卦属性
      orientation:BaguaOrientation.xi,//八卦方位
      trigram:[yinYang.yin,yinYang.yang,yinYang.yang],//三爻 
      viscera:[Viscera.feizang],//内脏
      kinsfolk:Kinsfolk.shaonv,//对应亲属
      trunk:Trunk.kou,//对应躯干
    },
    li:
    { 
      xtIndex:3,
      htIndex:9,
      name:'离',
      wuxing:WuXing.HUO,
      property:BaguaProperty.huo,//八卦属性
      orientation:BaguaOrientation.nan,//八卦方位
      trigram:[yinYang.yang,yinYang.yin,yinYang.yang],//三爻 
      viscera:[Viscera.xiaochang,Viscera.xinzang],//内脏
      kinsfolk:Kinsfolk.zhongnv,//对应亲属
      trunk:Trunk.mu,//对应躯干
    },
    zhen:
    { 
      xtIndex:4,
      htIndex:3,
      name:'震',
      wuxing:WuXing.MU,
      property:BaguaProperty.lei,//八卦属性
      orientation:BaguaOrientation.dong,//八卦方位
      trigram:[yinYang.yin,yinYang.yin,yinYang.yang],//三爻 
      viscera:[Viscera.dan],//内脏
      kinsfolk:Kinsfolk.zhangnan,//对应亲属
      trunk:Trunk.zu,//对应躯干
    },
    xun:
    { 
      xtIndex:5,
      htIndex:4,
      name:'巽',
      wuxing:WuXing.MU,
      property:BaguaProperty.feng,//八卦属性
      orientation:BaguaOrientation.dongnan,//八卦方位
      trigram:[yinYang.yang,yinYang.yang,yinYang.yin],//三爻 
      viscera:[Viscera.gan],//内脏
      kinsfolk:Kinsfolk.zhangnv,//对应亲属
      trunk:Trunk.gu,//对应躯干
    },
    kan:
    { 
      xtIndex:6,
      htIndex:1,
      name:'坎',
      wuxing:WuXing.SHUI,
      property:BaguaProperty.shui,//八卦属性
      orientation:BaguaOrientation.bei,//八卦方位
      trigram:[yinYang.yin,yinYang.yang,yinYang.yin],//三爻 
      viscera:[Viscera.pangguang,Viscera.shenzang],//内脏
      kinsfolk:Kinsfolk.zhongnan,//对应亲属
      trunk:Trunk.er,//对应躯干
    },
    gen: 
    { 
      xtIndex:7,
      htIndex:8,
      name:'艮',
      wuxing:WuXing.TU,
      property:BaguaProperty.shan,//八卦属性
      orientation:BaguaOrientation.dongbei,//八卦方位
      trigram:[yinYang.yang,yinYang.yin,yinYang.yin],//三爻 
      viscera:[Viscera.wei],//内脏
      kinsfolk:Kinsfolk.shaonan,//对应亲属
      trunk:Trunk.shou,//对应躯干
    },
    kun:
    { 
      xtIndex:8,
      htIndex:2,
      name:'坤',
      wuxing:WuXing.TU,
      property:BaguaProperty.di,//八卦属性
      orientation:BaguaOrientation.xinan,//八卦方位
      trigram:[yinYang.yin,yinYang.yin,yinYang.yin],//三爻 
      viscera:[Viscera.pi],//内脏
      kinsfolk:Kinsfolk.mu,//对应亲属
      trunk:Trunk.fu,//对应躯干
    }, };
     return map;
  }


  /**
   * 获取十二地支
   * @returns 
   */
  static DiZhiList(): Array<DiZhi> {
    let list: Array<DiZhi> =
      [{ index: 0,num:1, name: '子', wuXing: WuXing.SHUI, sixRen: SixRen.DAAN,brothers: 4},
      { index: 1,num:2, name: '丑', wuXing: WuXing.TU, sixRen: SixRen.LIULIAN ,brothers:7},
      { index: 2,num:3, name: '寅', wuXing: WuXing.MU, sixRen: SixRen.SHUXI ,brothers:4},
      { index: 3,num:4, name: '卯', wuXing: WuXing.MU, sixRen: SixRen.CHIKOU ,brothers:7},
      { index: 4,num:5, name: '辰', wuXing: WuXing.TU, sixRen: SixRen.XIAOJI ,brothers:10},
      { index: 5,num:6, name: '巳', wuXing: WuXing.HUO, sixRen: SixRen.KONGWANG,brothers:7 },
      { index: 6,num:7, name: '午', wuXing: WuXing.HUO, sixRen: SixRen.DAAN ,brothers:10},
      { index: 7,num:8, name: '未', wuXing: WuXing.TU, sixRen: SixRen.LIULIAN,brothers:1 },
      { index: 8,num:9, name: '申', wuXing: WuXing.JIN, sixRen: SixRen.SHUXI,brothers:10 },
      { index: 9,num:10, name: '酉', wuXing: WuXing.JIN, sixRen: SixRen.CHIKOU ,brothers:1},
      { index: 10,num:11, name: '戌', wuXing: WuXing.TU, sixRen: SixRen.XIAOJI,brothers: 4},
      { index: 11,num:0, name: '亥', wuXing: WuXing.SHUI, sixRen: SixRen.KONGWANG ,brothers:1}];
    return list;
  }

  /**
   * 地支
   * @param index 
   * @returns 
   */
  static getDizhi(index: number): DiZhi {
    if (index > 11) {
      index = index % 12;
    }
    let item = LSRUtils.DiZhiList()[index];
    return item;
  }

  /**
   * 六宫排列
   * @returns 
   */
  static getLiuRen(): Array<SixRentData> {
    let baguaData =  LSRUtils.getBagua()
    let list: Array<SixRentData> = [

  // 子午大安起青龙。 
// 丑未留恋起青龙。 
// 寅申速喜起青龙。 
// 卯酉赤口起青龙。 
// 辰戌小吉起青龙。 
// 巳亥空亡起青龙。
      { index: 1, name: '留恋',bgwuxing:WuXing.SHUI, sixRen: SixRen.LIULIAN, One: false, Two: false, OneName: "", TwoName: "", dizhi: null, stars: null, sixGod: null,sixRelations:"",shen:'',baguas:[baguaData.kan] },
      { index: 2, name: '速喜',bgwuxing:WuXing.HUO , sixRen: SixRen.SHUXI, One: false, Two: false, OneName: "", TwoName: "", dizhi: null, stars: null, sixGod: null ,sixRelations:"",shen:'',baguas:[baguaData.li]},
      { index: 3, name: '赤口',bgwuxing:WuXing.JIN, sixRen: SixRen.CHIKOU, One: false, Two: false, OneName: "", TwoName: "", dizhi: null, stars: null, sixGod:null ,sixRelations:"",shen:'',baguas:[baguaData.qian,baguaData.dui]},
      { index: 0, name: '大安',bgwuxing:WuXing.MU, sixRen: SixRen.DAAN, One: false, Two: false, OneName: "", TwoName: "", dizhi: null, stars: null, sixGod:null ,sixRelations:"",shen:'',baguas:[baguaData.zhen]},
      { index: 5, name: '空亡',bgwuxing:WuXing.TU, sixRen: SixRen.KONGWANG, One: false, Two: false, OneName: "", TwoName: "", dizhi: null, stars: null, sixGod: null ,sixRelations:"",shen:'',baguas:[baguaData.gen,baguaData.kun]},
      { index: 4, name: '小吉',bgwuxing:WuXing.MU, sixRen: SixRen.XIAOJI, One: true, Two: false, OneName: "", TwoName: "", dizhi: null, stars: null, sixGod: null,sixRelations:"",shen:'',baguas: [baguaData.xun]}
    ];
    return list;
  }

  /**
   * 五行克制关系
   * @returns 
   */
  static getMutualRestraint(): Array<WxShengKe> { 

    /**
     * 五行相生相克
     * 以自身地支为准，与其它宫地支论生克： 
    生我者为父母，克我者为官鬼， 
    我生者为子孙，我克者为妻财， 
    与我同类者为兄弟。 
     */
    let list: Array<WxShengKe> = [
      { index: 0, wuxing: WuXing.JIN, toWo: WuXing.TU, woTo: WuXing.SHUI, killWO: WuXing.HUO, woKill: WuXing.MU, same: WuXing.TU },
      { index: 1, wuxing: WuXing.MU, toWo: WuXing.SHUI, woTo: WuXing.HUO, killWO: WuXing.JIN, woKill: WuXing.TU, same: WuXing.TU },
      { index: 2, wuxing: WuXing.SHUI, toWo: WuXing.JIN, woTo: WuXing.MU, killWO: WuXing.TU, woKill: WuXing.HUO, same: WuXing.TU },
      { index: 3, wuxing: WuXing.HUO, toWo: WuXing.MU, woTo: WuXing.TU, killWO: WuXing.SHUI, woKill: WuXing.JIN, same: WuXing.TU },
      { index: 4, wuxing: WuXing.TU, toWo: WuXing.HUO, woTo: WuXing.JIN, killWO: WuXing.MU, woKill: WuXing.SHUI, same: WuXing.TU },
    ];
    return list;
  }


  /**
   * 六神对应五行
   * @returns 
   */
  static getSixGodWuXing(): Array<SixGodWuXing> { 

    /** 
 青龙（木）、朱雀（火）、勾陈（土）、白虎（金）、玄武（水）、螣蛇（土）
     */
    let list: Array<SixGodWuXing> = [
      { index: SixGod.QINLONG, wuxing: WuXing.MU, },
      { index: SixGod.ZHUQIE, wuxing: WuXing.HUO, },
      { index: SixGod.GOUCHEN,wuxing: WuXing.TU, },
      { index: SixGod.BAIHU, wuxing: WuXing.JIN, },
      { index: SixGod.XUANWU, wuxing: WuXing.SHUI,  },
      { index: SixGod.TENGSHE, wuxing: WuXing.TU,  }
    ];
    return list;
  }

  /**
   * 六神对应五行
   * @returns 
   */
  static getFiveStarsWuXing(): Array<FiveStarsWuXing> { 

    /**
     木星=字体绿色（和木的色块一样）
火星=字体红色（和火的色块一样）
土星=字体褐色（和土的色块一样）
金星=字体橘黄色色（和金的色块一样）
水星=字体蓝色（和水的色块一样）
天空=黑色
     */
    let list: Array<FiveStarsWuXing> = [
      { index: FiveStars.MUXING, wuxing: WuXing.MU, },
      { index: FiveStars.HUOXING, wuxing: WuXing.HUO, },
      { index: FiveStars.TUXING,wuxing: WuXing.TU, },
      { index: FiveStars.JINXING, wuxing: WuXing.JIN, },
      { index: FiveStars.SHUIXING, wuxing: WuXing.SHUI,  },
      { index: FiveStars.TIANKONG, wuxing: -1,  }
    ];
    return list;
  }


  

  


  /**
   * 计算六宫的十二地支
   * @param a //六壬宫
   * @param b 
   * @param targetIndex 
   * @param targetValue 
   */
  static GroundExhaustBranch(a: Array<SixRentData>, b: Array<DiZhi>, targetIndex: number, targetValue: number) {
    // 根据`index`属性对数组`a`进行排序
    const sortedA = a.slice().sort((x, y) => x.index - y.index);
 
    // 查找目标值在数组b中的索引
    const startIndex = b.findIndex(item => item.index === targetValue);
    if (startIndex === -1) {
      console.log("Target value not found in b array.");
      return null;
    }

    // 计算sortedA数组中每个元素在b数组中的位置
    const positions = sortedA.map((item, index) => {
      const pos = (startIndex + 2 * (index - targetIndex) + b.length) % b.length;
      return b[pos];
    });

 
    // 使用对应的dizhi更新sortedA数组
    sortedA.forEach((item, index) => {
      if (positions[index]) {
        item.dizhi = positions[index];
      }
    });


 
    //基于`sortedA`更新原始数组`a`
    sortedA.forEach((sortedItem) => {
      const originalItem = a.find(item => item.index === sortedItem.index);
      if (originalItem) {
        originalItem.dizhi = sortedItem.dizhi;
      }
    });
 
  }

  /**
   * 六宫对应五星
   * @param a 
   * @param c 
   * @param targetIndex 
   * @param targetValue 
   * @returns 
   */
  static UpFiveStars(a: Array<SixRentData>, c: Array<FiveStarsWuXing>, targetIndex: number, targetValue: number) {
    // Sort the array `a` based on the `index` property
    const sortedA = a.slice().sort((x, y) => x.index - y.index);

    // // Find the index of the targetValue in the c array
    // const startIndex = c.findIndex(item => item === targetValue);
    // if (startIndex === -1) {
    //     console.log("Target value not found in c array.");
    //     return;
    // }

    // Calculate the positions in the c array for each element in the sortedA array
    const positions = sortedA.map((item, index) => {
      const pos = (targetValue + (index - targetIndex) + c.length) % c.length;
      return c[pos];
    }); 
    //用对应的天体更新sortedA数组
    sortedA.forEach((item, index) => {
      if (positions[index]) {
        item.stars = positions[index];
      }
    });

    //基于`sortedA`更新原始数组`a`
    sortedA.forEach((sortedItem) => {
      const originalItem = a.find(item => item.index === sortedItem.index);
      if (originalItem) {
        originalItem.stars = sortedItem.stars;
      }
    });
  }
  
  /**
   * 请六神
   * @param a 
   * @param c 
   * @param targetIndex 
   * @param targetValue 
   */
  static PleaseSixGods(a: Array<SixRentData>, c: Array<SixGodWuXing>, targetIndex: number, targetValue: number) {
    // Sort the array `a` based on the `index` property
    const sortedA = a.slice().sort((x, y) => x.index - y.index);

    // Calculate the positions in the c array for each element in the sortedA array
    const positions = sortedA.map((item, index) => {
      const pos = (targetValue + (index - targetIndex) + c.length) % c.length;
      return c[pos];
    }); 
    //用对应的天体更新sortedA数组
    sortedA.forEach((item, index) => {
      if (positions[index]) {
        item.sixGod = positions[index];
      }
    });

    //基于`sortedA`更新原始数组`a`
    sortedA.forEach((sortedItem) => {
      const originalItem = a.find(item => item.index === sortedItem.index);
      if (originalItem) {
        originalItem.sixGod = sortedItem.sixGod;
      }
    });
  }


  /**
   * 算六亲
   * @param a 
   * @param c 
   * @param targetIndex 
   */
  static  SixRelationsLocation(a: Array<SixRentData>, c: Array<WxShengKe>, targetIndex: number)
  {
        let zishen = a[targetIndex];
        let wuxing = zishen.dizhi?.wuXing;
        if(wuxing!=null&& zishen.dizhi!=null)
        {
          const positions = c.filter((item, index) => {
                if(item.wuxing==wuxing ) 
                {
                  return  item;
                } 
           }); 
//  // 过滤出五行属性为土的地支  wuXing: 
//           const tuDiZhi = LSRUtils.DiZhiList().filter(dz => dz.wuXing === WuXing.TU);
//           //丑辰未戌
 
//           const tuIndex = zishen.dizhi.index % 2 === 0 ? ( zishen.dizhi.index / 2) % tuDiZhi.length : ((zishen.dizhi.index + 1) / 2) % tuDiZhi.length;
       
           
          // 0 1  2 3  4 5 6 7  8 9 10 11
          // 子丑 寅卯 辰巳 午未 申酉 戌亥
          // 水土 木木 土火 火土 金金 土水
 
          if(positions!=null&&positions.length>0)
          {
            a.forEach((item) => {
            //  console.log(item);
            //  console.log(zishen.dizhi?.brothers+'=>'+item.dizhi?.index);
                //  生我者为父母，克我者为官鬼， 
              //  我生者为子孙，我克者为妻财，  
               if(item.index==zishen.index)
               {
             
                  item.shen ="身"; 
                  const wxxk = LSRUtils.getMutualRestraint().filter(wx => wx.index === item.dizhi?.wuXing);
                  if(wxxk.length==1)
                  {
                      //地支上的五行和八卦上的五行对比
                      if( wxxk[0].wuxing==item.bgwuxing)
                      {
                           item.sixRelations ="兄弟";
                      }
                      else if(wxxk[0].toWo==item.bgwuxing)
                      {
                          item.sixRelations ="父母"
                      }
                      else if(wxxk[0].woTo==item.bgwuxing)
                        {
                            item.sixRelations ="子孙"
                        }
                        else if(wxxk[0].killWO==item.bgwuxing)
                          {
                              item.sixRelations ="官鬼"
                          }
                          else if(wxxk[0].woKill==item.bgwuxing)
                            {
                                item.sixRelations ="妻财"
                            }
                  }


               } 
               else if(zishen.dizhi?.brothers===item.dizhi?.index) {
                   item.sixRelations ="兄弟";
               }  
               else if (item.dizhi?.wuXing==positions[0]?.toWo&& item.sixRelations=='') {
                      item.sixRelations ="父母"
                }
                else if (item.dizhi?.wuXing==positions[0]?.killWO&& item.sixRelations=='') {
                   item.sixRelations ="官鬼"
                } 
                else if (item.dizhi?.wuXing==positions[0]?.woTo&& item.sixRelations=='') {
                   item.sixRelations ="子孙"
                }
                else if (item.dizhi?.wuXing==positions[0]?.woKill&& item.sixRelations=='') {
                    item.sixRelations ="妻财"
                } 
            
             });
          }




// // 定义地支和五行属性数组
// const dizhi1 = ["子", "丑", "寅", "卯", "辰", "巳", "午", "未", "申", "酉", "戌", "亥"];
// const wuxing1 = ["水", "土", "木", "木", "土", "火", "火", "土", "金", "金", "土", "水"];

// // 定义一个对象存储五行的生克关系
// const wuxingRelations1 = {
//     "水": { "生": "木", "克": "火" },
//     "木": { "生": "火", "克": "土" },
//     "火": { "生": "土", "克": "金" },
//     "土": { "生": "金", "克": "水" },
//     "金": { "生": "水", "克": "木" }
// };


// // 打印地支信息
// const dizhiInfo = LSRUtils.generateDizhiInfo(wuxing1,dizhi1,wuxingRelations1);
// dizhiInfo.forEach(info => {
//   console.log(`${info.name} (${info.wuxing}) - 兄弟: ${info.brothers.join(", ")} - 父母: ${info.parents.join(", ")}`);
// });
   }
      }
      


// // 计算兄弟
// static calculateBrothers(index:number,wuxing:Array<any>,dizhi:Array<any>)  {
//   const currentElement = wuxing[index];
//   const brothers = [];
//   for (let i = 0; i < wuxing.length; i++) {
//       if (i !== index && wuxing[i] === currentElement) {
//           brothers.push(dizhi[i]);
//       }
//   }
//   return brothers;
// }

// // 计算父母
// static calculateParents  (index:number,wuxing:Array<any>,dizhi:Array<any>,wuxingRelations:any)   {
//   const currentElement = wuxing[index];
//   const parents = [];
//   for (let i = 0; i < wuxing.length; i++) {
//       if (wuxingRelations[currentElement]["克"] === wuxing[i]) {
//           parents.push(dizhi[i]);
//       }
//   }
//   return parents;
// }

// // 生成地支信息
// static generateDizhiInfo   (wuxing:Array<any>,dizhi:Array<any>,wuxingRelations:any)  {
//   const dizhiInfo = dizhi.map((d, i) => {
//       return {
//           name: d,
//           wuxing: wuxing[i],
//           brothers: LSRUtils.calculateBrothers(i,wuxing,dizhi),
//           parents: LSRUtils.calculateParents(i,wuxing,dizhi,wuxingRelations)
//       };
//   });
//   return dizhiInfo;
// }


}